package cn.ctvonline.android.kaopu.activity;

import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.ctvonline.android.kaopu.R;
import cn.ctvonline.android.kaopu.base.BaseActionBarActivity;
import cn.ctvonline.android.kaopu.base.BaseFragment;
import cn.ctvonline.android.kaopu.base.util.ToastUtil;
import cn.ctvonline.android.kaopu.base.util.WindowUtil;
import cn.ctvonline.android.kaopu.fragment.DiscoverFragment;
import cn.ctvonline.android.kaopu.fragment.FeatureFragment;
import cn.ctvonline.android.kaopu.fragment.FrontpageFragment;
import cn.ctvonline.android.kaopu.fragment.GroupFragment;
import cn.ctvonline.android.kaopu.fragment.UserFragment;
import cn.ctvonline.android.kaopu.widget.view.LazyViewPager;

public class MainActivity extends BaseActionBarActivity {
    private Map<Integer, String> toolbarMap;
    private List<BaseFragment> fragments;
    private LazyPagerAdapter adapter;
    private MenuItem searchItem, settingItem, shareItem;
    @Bind(R.id.main_frontpage_rb)
    RadioButton frontpageRb;
    @Bind(R.id.main_group_rb)
    RadioButton groupRb;
    @Bind(R.id.main_feature_rb)
    RadioButton featureRb;
    @Bind(R.id.main_found_rb)
    RadioButton foundRn;
    @Bind(R.id.main_mine_rb)
    RadioButton mineRb;
    private List<RadioButton> radioBtnList;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.main_lazy_vp)
    LazyViewPager lazyVp;
    int currentCheckedIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WindowUtil.translucentStatusBar(this, true);
        WindowUtil.setTranslucentStatus(this, true);
        setContentView(R.layout.activity_main);
        initViews();
        initFragments();
        ViewGroup decorView = (ViewGroup) getWindow().getDecorView();
        ViewGroup decorChild = (ViewGroup) decorView.getChildAt(0);
    }

    private void initViews() {
        ButterKnife.bind(this);
        toolbar.setLogo(R.mipmap.logo);
        setSupportActionBar(toolbar);
        toolbar.setOnMenuItemClickListener(new SimpleOnMenuItemClickListener());
        toolbarMap = new HashMap<>();
        toolbarMap.put(0, "首页");
        toolbarMap.put(1, "圈子");
        toolbarMap.put(2, "精选");
        toolbarMap.put(3, "发现");
        toolbarMap.put(4, "我的");
        radioBtnList = new ArrayList<>();
        radioBtnList.add(frontpageRb);
        radioBtnList.add(groupRb);
        radioBtnList.add(featureRb);
        radioBtnList.add(foundRn);
        radioBtnList.add(mineRb);
        RadioClickListener radioListener = new RadioClickListener();
        for (RadioButton radio : radioBtnList) {
            radio.setOnClickListener(radioListener);
        }
    }

    class RadioClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if (v == frontpageRb) {
                currentCheckedIndex = 0;
                searchItem.setVisible(true);
                shareItem.setVisible(false);
            } else if (v == groupRb) {
                currentCheckedIndex = 1;
//                ((GroupFragment)fragments.get(currentCheckedIndex)).doRefersh(false);
                searchItem.setVisible(false);
                shareItem.setVisible(false);
            } else if (v == featureRb) {
                currentCheckedIndex = 2;
                searchItem.setVisible(true);
                shareItem.setVisible(false);
            } else if (v == foundRn) {
                currentCheckedIndex = 3;
                searchItem.setVisible(true);
                shareItem.setVisible(false);
            } else if (v == mineRb) {
                currentCheckedIndex = 4;
                searchItem.setVisible(true);
                shareItem.setVisible(false);
            }
            for (int i = 0; i < radioBtnList.size(); i++) {
                if (i == currentCheckedIndex) {
                    radioBtnList.get(i).setChecked(true);
                } else {
                    radioBtnList.get(i).setChecked(false);
                }
            }
            lazyVp.setCurrentItem(currentCheckedIndex);
        }
    }

    private void initFragments() {
        fragments = new ArrayList<>();
        fragments.add(new FrontpageFragment());
        fragments.add(new GroupFragment());
        fragments.add(new FeatureFragment());
        fragments.add(new DiscoverFragment());
        fragments.add(new UserFragment());
        adapter = new LazyPagerAdapter(getSupportFragmentManager(), fragments);
        lazyVp.setAdapter(adapter);
        lazyVp.setOffscreenPageLimit(fragments.size());
        lazyVp.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                String title = toolbarMap.get(position);
                toolbar.setTitle(title);
            }
        });
        radioBtnList.get(0).setChecked(true);
    }

    class SimpleOnMenuItemClickListener implements Toolbar.OnMenuItemClickListener {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.action_search:
                    Intent intent = new Intent(getApplicationContext(), cn.ctvonline.android.kaopu.activity.SearchableActivity.class);
                    startActivity(intent);
                    break;
                case R.id.action_settings:
                    ToastUtil.show(getApplicationContext(), "action setting");
                    break;
                case R.id.action_share:
                    ToastUtil.show(getApplicationContext(), "action share");
                    break;
            }
            return true;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_search, menu);
        searchItem = menu.findItem(R.id.action_search);
        settingItem = menu.findItem(R.id.action_settings);
        shareItem = menu.findItem(R.id.action_share);
        shareItem.setIcon(R.drawable.fenxiang_selector);
        /**
         * 禁止展开
         */
        MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
                return false;
            }

            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {
                return false;
            }
        });
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) searchItem.getActionView();
        Log.i(TAG, "search view is " + searchView);
        if (searchView != null) {
            searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        } else if (id == R.id.action_share) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private long lastBackTime;

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - lastBackTime < 2000) {
            finish();
            System.exit(0);
        } else {
            Toast.makeText(getApplicationContext(), "再按一次退出", Toast.LENGTH_SHORT).show();
            lastBackTime = System.currentTimeMillis();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    class LazyPagerAdapter extends FragmentPagerAdapter {
        List<BaseFragment> fragList;

        public LazyPagerAdapter(FragmentManager fm, List<BaseFragment> fragList) {
            super(fm);
            this.fragList = fragList;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            return super.instantiateItem(container, position);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            super.destroyItem(container, position, object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return super.isViewFromObject(view, object);
        }

        @Override
        public Fragment getItem(int position) {
            return fragList.get(position);
        }

        public int getItemPosition(Object object) {
            return fragList.indexOf(object);
        }

        @Override
        public int getCount() {
            return fragList.size();
        }
    }

    @Override
    protected void onDestroy() {
        for (BaseFragment fragment : fragments) {
            fragment.onDestroy();
        }
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        overridePendingTransition(0, 0);
        super.onPause();
    }

    @Override
    protected String generatePageName() {
        return "MainActivity page";
    }
}
